package za.co.dylanjaneke.airdownloader.command
{
	import mx.controls.Alert;
	import mx.rpc.events.ResultEvent;
	import mx.utils.StringUtil;
	
	import za.co.dylanjaneke.airdownloader.controller.data.ConnectionManager;
	import za.co.dylanjaneke.airdownloader.events.NewDownloadSiteEvent;
	import za.co.dylanjaneke.airdownloader.model.SettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.TrackerSettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.vo.DBVO;
	import za.co.dylanjaneke.airdownloader.model.vo.DownloadSiteVO;

	/**
	 * Author: Dylan Janeke.
	 */
	[Name("newDownloadSiteCommand")]
	public class NewDownloadSiteCommand
	{
		[Inject]
		public var repo:ConnectionManager;
		
		[Inject]
		public var settingsScreenPM:TrackerSettingsScreenPM;
		
		[Observer]
		public function handleNewDownloadSiteEvent(event:NewDownloadSiteEvent): void
		{
			var vo:DownloadSiteVO= new DownloadSiteVO();
			vo.url= event.url.replace("http://","").replace("www.","");
			vo.url= StringUtil.trim(vo.url);
			
			for each (var dbvo:DownloadSiteVO in settingsScreenPM.sites)
			{
				if(dbvo.url== vo.url)
				{
					Alert.show("Site: " + vo.url +", already exists.","Error");
					return;
				}
			}
			
			repo.executeStatement(
				DownloadSiteVO.createInsert(vo, 
					repo.createStatement()));
			
			settingsScreenPM.sites.addItem(vo);
		}
	}
}